﻿using System;
using System.IO;
using System.Activities;
using System.Security;
using Reactor.Workflow.Activities;

namespace Reactor.ServiceGrid.Workflows.Activities
{

    public sealed class DeleteServiceDirectory : ReactorCodeActivityBase
    {
        [RequiredArgument]
        public InArgument<string> TargetServiceInstallPath { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            var serviceInstallDirectory = context.GetValue(TargetServiceInstallPath);

            var directory = new DirectoryInfo(serviceInstallDirectory);

            try
            {
                if (Log.IsDebugEnabled) Log.DebugFormat("Attempting to delete service directory at: {0}", directory.FullName);
                directory.Delete(true);

                if (Log.IsDebugEnabled) Log.Debug("Service directory successfully deleted.");
            }
            catch (UnauthorizedAccessException unauthorizedAccessException)
            {
                // The directory contains a read-only file
                // TODO: Support read only files by marking them write-only and trying again.
                Log.Error("Unable to delete service install directory. This can be caused by the directory containing a read-only file.", unauthorizedAccessException);
            }
            catch (DirectoryNotFoundException directoryNotFoundException)
            {
                Log.Error("Unable to delete service install directory because it was not found", directoryNotFoundException);
            }
            catch (IOException ioException)
            {
                /*
                 *  The directory is read-only.
                        -or-
                    The directory contains one or more files or subdirectories and recursive is false.
                        -or-
                    The directory is the application's current working directory.
                */
                Log.Error("Unable to delete service install directory. This could have been caused by the directory being read-only, or the directory is the applications current working directory.", ioException); 
            }
            catch (SecurityException securityException)
            {
                // The caller does not have the required permission
                Log.Error("Unable to delete service install directory because the caller does not have the required permission.", securityException);
            }
        }
    }
}
